package com.qingluan.dd.InetTool;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.qingluan.Database.MissionDataBase;
import com.qingluan.arguments.ARGUMENTS;
import com.qingluan.widget.DragListViewAdapter;

public class IndexInitializationInfo {
	private AsyncHttpClient client;
	private RequestParams params;
	private String uid ;
	private final Context context_this_activity;
	public IndexInitializationInfo(String uid,Context context){
		this.uid = uid;
		this.context_this_activity = context;
	}
	
	/*
	 * for refresh the information in index-activity 
	 */
	public void RefershInfoPost(String url,DragListViewAdapter adapter,final setRefreshInfo refreshinfo){
		client = new AsyncHttpClient();
		client.setTimeout(10000);
		params = new RequestParams();
		
	
		JSONArray jsonObject = new JSONArray();
		if (adapter.getObjIds() != null){
			for (String id : adapter.getObjIds()){
				jsonObject.put(id);
			}
		}else {
			
		}
		JSONObject json = new JSONObject();
		
		try {
			json.put("uid", this.uid);
			json.put("ids", jsonObject);
	
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		params.put("JSON_NEW_ITEM", json.toString());//join user id to identity;

		Log.d("internet argument","url "+url+this.uid);
		Log.d("internet argument","argu "+ARGUMENTS.POST_ARGUMENT_INDEX);
		
		client.post(url, params,new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String res){
				refreshinfo.RefreshView(res);
			}
			
			@Override
			public void onFailure(int statusCode, Header[] headers, byte[] binaryData, Throwable error){
				Log.d("internet_work","error"+error.toString());
				Toast.makeText(context_this_activity, "No internet", Toast.LENGTH_SHORT).show();
				refreshinfo.Failed();
			}

		});
		
	}
	
	public void RefreshInfoGet(String url,final setOnRefreshInfo refresh){
		client = new AsyncHttpClient();
		client.setTimeout(10000);
		client.get(	url, new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String res){
				refresh.RefreshView(res);
			}
		});
	}
	/*
	 * deal with the Information to update index-activity
	 */
	public  interface setRefreshInfo{
		public void RefreshView(String result);
		public void Failed();
	}
	
	/*
	 * deal with Information that was  pulled  down.
	 * 
	 */
	public interface setOnRefreshInfo{
		public void RefreshView(String result);
		public void Failed();
	}
}	